<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
  >
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="动态ID" prop="postId">
        <el-input v-model="dataForm.postId" placeholder="动态ID"></el-input>
      </el-form-item>
      <el-form-item label="评论内容" prop="content">
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入评论内容"
          v-model="dataForm.content">
        </el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'CommentsAddOrUpdate',
  data () {
    return {
      visible: false,
      dataForm: {
        commentId: 0,
        postId: '',
        userId: '',
        content: ''
      },
      dataRule: {
        postId: [
          { required: true, message: '动态ID不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '评论内容不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init (id) {
      this.dataForm.commentId = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.commentId) {
          this.$http({
            url: this.$http.adornUrl(`/community/comments/info/${this.dataForm.commentId}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.postId = data.comment.postId
              this.dataForm.userId = data.comment.userId
              this.dataForm.content = data.comment.content
            }
          })
        }
      })
    },
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/community/comments/${!this.dataForm.commentId ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'commentId': this.dataForm.commentId || undefined,
              'postId': this.dataForm.postId,
              'userId': this.dataForm.userId,
              'content': this.dataForm.content
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script> 